<template>
  <view class="album-list-container">
    <view class="header">
      <text class="title">家庭相册</text>
      <view class="header-actions">
        <button class="ai-chat-btn" @click="showAiChatDialog = true">
          <text class="icon">AI</text> AI画图
        </button>
        <button class="create-btn" @click="createAlbum">
          <text class="icon">+</text> 创建相册
        </button>
      </view>
    </view>
    
    <scroll-view scroll-y class="album-grid-container" @refresherrefresh="onRefresh" :refresher-enabled="true" :refresher-triggered="isRefreshing">
      <view class="album-grid" v-if="albums.length > 0">
        <view 
          class="album-item" 
          v-for="album in albums" 
          :key="album.id"
          @click="goToAlbumDetail(album.id)"
        >
          <image 
            class="album-cover" 
            :src="safeImageUrl(album.coverUrl, 'album')"
            mode="aspectFill"
          />
          <view class="album-info">
            <text class="album-name">{{ album.name }}</text>
            <view class="album-meta">
              <text class="photo-count">{{ album.photoCount || 0 }}张照片</text>
              <view class="creator-info" v-if="album.creator">
                <image class="creator-avatar" :src="safeImageUrl(album.creator.avatarUrl, 'avatar')" />
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <view class="empty-state" v-if="albums.length === 0 && !loading">
        <image class="empty-icon" :src="imageHelper.getDefaultAlbum()" mode="aspectFit" />
        <text class="empty-text">还没有相册，快来创建第一个吧~</text>
        <button class="create-album-btn" @click="createAlbum">创建第一个相册</button>
      </view>
    </scroll-view>

    <view class="loading-state" v-if="loading && !isRefreshing">
      <uni-load-more status="loading"></uni-load-more>
    </view>

    <!-- AI对话画图弹窗 -->
    <view class="ai-chat-modal" v-if="showAiChatDialog" catchtouchmove="true" @tap="closeAiChatDialog">
      <view class="chat-container" @tap.stop>
        <view class="chat-header">
          <text class="chat-title">AI画图助手</text>
          <text class="close-btn" @tap="closeAiChatDialog">×</text>
        </view>
        
        <!-- 对话区域 -->
        <scroll-view scroll-y class="chat-messages" :scroll-top="scrollTop" :scroll-with-animation="false">
          <view class="message-list">
            <!-- 欢迎消息 -->
            <view class="message ai-message" v-if="chatMessages.length === 0">
              <view class="message-avatar">AI</view>
              <view class="message-content">
                <text class="message-text">你好！我是AI画图助手，告诉我你想要什么样的图片，我来为你生成～</text>
              </view>
            </view>
            
            <!-- 对话消息 -->
            <view 
              class="message" 
              :class="message.type === 'user' ? 'user-message' : 'ai-message'"
              v-for="(message, index) in chatMessages" 
              :key="index"
            >
              <!-- AI消息：头像在左，内容在右 -->
              <template v-if="message.type === 'ai'">
                <view class="message-avatar">AI</view>
                <view class="message-content">
                  <text class="message-text" v-if="message.text">{{ message.text }}</text>
                  
                  <!-- 生成的图片 -->
                  <view class="generated-image" v-if="message.image">
                    <image 
                      class="ai-image" 
                      :src="message.image" 
                      mode="aspectFill"
                      @tap="previewImage(message.image)"
                    />
                  </view>
                  
                  <!-- 加载状态 -->
                  <view class="loading-message" v-if="message.loading">
                    <text class="loading-text">正在生成图片...</text>
                    <view class="loading-dots">
                      <text class="dot">.</text>
                      <text class="dot">.</text>
                      <text class="dot">.</text>
                    </view>
                  </view>
                </view>
              </template>
              
              <!-- 用户消息：内容在左，头像在右 -->
              <template v-else>
                <view class="message-content">
                  <text class="message-text">{{ message.text }}</text>
                </view>
                <view class="message-avatar">我</view>
              </template>
            </view>
          </view>
        </scroll-view>
        
        <!-- 输入区域 -->
        <view class="chat-input-area">
          <input 
            class="chat-input" 
            v-model="currentInput" 
            placeholder="描述你想要的图片..." 
            @confirm="sendMessage"
            confirm-type="send"
          />
          <button 
            class="send-btn" 
            @tap="sendMessage"
            :disabled="!currentInput.trim() || isGenerating"
          >
            {{ isGenerating ? '...' : '发送' }}
          </button>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import imageHelper from '@/utils/imageHelper'
import config from '@/utils/config.js'
import { api } from '@/utils/request.js'

export default {
  name: 'AlbumList',
  data() {
    return {
      loading: false,
      isRefreshing: false,
      imageHelper,
      // AI对话画图相关
      showAiChatDialog: false,
      isGenerating: false,
      currentInput: '',
      chatMessages: [],
      scrollTop: 0
    }
  },
  
  computed: {
    ...mapState('album', ['albums'])
  },

  onShow() {
    this.loadAlbums()
  },
  
  onPullDownRefresh() {
    this.onRefresh();
  },

  methods: {
    ...mapActions('album', ['fetchAlbums']),

    async loadAlbums() {
      if (this.loading) return;
      this.loading = true
      try {
        console.log('开始加载相册列表...')
        const albums = await this.fetchAlbums()
        console.log('获取到的相册:', albums)
        console.log('当前store中的相册:', this.albums)
      } catch (error) {
        console.error('加载相册列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    async onRefresh() {
      this.isRefreshing = true;
      try {
        await this.fetchAlbums();
      } catch (error) {
        console.error('刷新相册列表失败:', error);
      } finally {
        this.isRefreshing = false;
        uni.stopPullDownRefresh();
      }
    },

    goToAlbumDetail(albumId) {
      if (!albumId) return
      uni.navigateTo({
        url: `/pages/album/detail?albumId=${albumId}`
      })
    },

    createAlbum() {
      uni.navigateTo({
        url: '/pages/album/create'
      })
    },

    safeImageUrl(url, type = 'album') {
      if (!url) {
        return type === 'avatar' ? imageHelper.getDefaultAvatar() : imageHelper.getDefaultCover();
      }
      return imageHelper.safeImageUrl(url, type);
    },

    // AI对话画图相关方法
    closeAiChatDialog() {
      this.showAiChatDialog = false;
      this.resetChatData();
    },

    resetChatData() {
      this.currentInput = '';
      this.chatMessages = [];
      this.scrollTop = 0;
    },

    // 发送消息并生成图片
    async sendMessage() {
      if (!this.currentInput.trim() || this.isGenerating) {
        return;
      }

      const userMessage = this.currentInput.trim();
      this.currentInput = '';

      // 添加用户消息
      this.chatMessages.push({
        type: 'user',
        text: userMessage,
        timestamp: Date.now()
      });

      // 添加AI加载消息
      const loadingMessageIndex = this.chatMessages.length;
      this.chatMessages.push({
        type: 'ai',
        loading: true,
        timestamp: Date.now()
      });

      this.scrollToBottom();
      this.isGenerating = true;

      try {
        const response = await api.post(config.getImageGenerateUrl(), {
          prompt: userMessage,
          size: '1024x1024'
        });

        console.log('AI生成响应:', response);
        
        // 检查响应是否成功
        if (response.code === 200 && response.data) {
          let imageUrl = response.data;
          
          // 如果返回的是对象（旧格式兼容）
          if (typeof response.data === 'object' && response.data.imageUrl) {
            imageUrl = response.data.imageUrl;
          }
          
          // 确保有有效的图片URL
          if (typeof imageUrl === 'string' && imageUrl.trim()) {
            const fullImageUrl = imageHelper.safeImageUrl(imageUrl);
            console.log('构建的图片URL:', fullImageUrl);
            console.log('原始imageUrl:', imageUrl);
            
            // 替换加载消息为生成的图片
            this.chatMessages[loadingMessageIndex] = {
              type: 'ai',
              text: '为你生成了这张图片：',
              image: fullImageUrl, // 使用 imageHelper 来构建完整的URL
              timestamp: Date.now()
            };
          } else {
            throw new Error('生成的图片URL格式不正确');
          }
        } else {
          // 替换加载消息为错误消息
          const errorMessage = response.message || 'AI图片生成失败';
          throw new Error(errorMessage);
        }
      } catch (error) {
        console.error('AI图片生成失败:', error);
        // 替换加载消息为错误消息
        this.chatMessages[loadingMessageIndex] = {
          type: 'ai',
          text: `抱歉，生成图片时出现了问题：${error.message || '请稍后重试'}`,
          timestamp: Date.now()
        };
      } finally {
        this.isGenerating = false;
        this.scrollToBottom();
      }
    },

    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        this.scrollTop = 999999;
      });
    },

    // 预览图片
    previewImage(imageUrl) {
      const urlToPreview = typeof imageUrl === 'object' ? imageUrl.image : imageUrl;
      if (typeof urlToPreview !== 'string' || !urlToPreview) {
        console.error('预览失败，图片URL无效:', urlToPreview);
        uni.showToast({
          title: '无法预览图片',
          icon: 'none'
        });
        return;
      }
      uni.previewImage({
        urls: [urlToPreview],
        current: urlToPreview
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.album-list-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fafafa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  
  .title {
    font-size: 28rpx;
    font-weight: 500;
    color: #1a1a1a;
  }

  .header-actions {
    display: flex;
    gap: 12rpx;
  }

  .ai-chat-btn {
    display: flex;
    align-items: center;
    background: #e74c3c;
    color: white;
    font-size: 22rpx;
    padding: 8rpx 12rpx;
    border-radius: 6rpx;
    border: none;
    .icon {
      margin-right: 4rpx;
      font-size: 20rpx;
    }
  }

  .create-btn {
    display: flex;
    align-items: center;
    background: #34495e;
    color: white;
    font-size: 22rpx;
    padding: 8rpx 12rpx;
    border-radius: 6rpx;
    border: none;
    .icon {
      margin-right: 4rpx;
      font-size: 24rpx;
    }
  }
}

.album-grid-container {
  flex: 1;
  overflow-y: auto;
  width: 100%;
  box-sizing: border-box;
}

.album-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12rpx;
  padding: 16rpx;
  box-sizing: border-box;
}

.album-item {
  background: white;
  border-radius: 12rpx;
  overflow: hidden;
  border: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  
  .album-cover {
    width: 100%;
    height: 200rpx;
    background-color: #f5f5f5;
  }
  
  .album-info {
    padding: 16rpx;
    
    .album-name {
      font-size: 26rpx;
      font-weight: 500;
      color: #2c3e50;
      margin-bottom: 8rpx;
      display: block;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .album-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .photo-count {
        font-size: 22rpx;
        color: #95a5a6;
      }
      
      .creator-info {
        .creator-avatar {
          width: 32rpx;
          height: 32rpx;
          border-radius: 16rpx;
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 160rpx;
  
  .empty-icon {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 24rpx;
    opacity: 0.4;
  }
  
  .empty-text {
    font-size: 24rpx;
    color: #95a5a6;
    margin-bottom: 32rpx;
  }

  .create-album-btn {
    background: #34495e;
    color: white;
    font-size: 24rpx;
    padding: 12rpx 32rpx;
    border-radius: 8rpx;
    border: none;
  }
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 120rpx;
}

// AI对话画图弹窗样式
.ai-chat-modal {
  z-index: 9999;            // 提高到最顶
  position: fixed; top:0; right:0; bottom:0; left:0;
  background: rgba(0,0,0,.5);
  transform: translateZ(0); // 独立合成层，避免闪烁
  backface-visibility: hidden;
  will-change: transform;
  
  .chat-container {
    background: #fff;
    transform: translateZ(0);
    backface-visibility: hidden;
    will-change: transform;
    border-radius: 24rpx;
    width: 95%;
    max-width: 750rpx;
    height: 85vh;
    max-height: 1200rpx;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    margin: 0 auto;
    
    .chat-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx;
      border-bottom: 1px solid #f0f0f0;
      background: #34495e;
      color: white;
      
      .chat-title {
        font-size: 26rpx;
        font-weight: 500;
      }
      
      .close-btn {
        font-size: 32rpx;
        color: white;
        width: 48rpx;
        height: 48rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    
    .chat-messages {
      flex: 1;
      padding: 20rpx;
      overflow-y: auto;
      
      .message-list {
        .message {
          display: flex;
          margin-bottom: 32rpx;
          
                      &.user-message {
              justify-content: flex-end;
              
              .message-content {
                background: #34495e;
                color: white;
                margin-left: 20rpx;
                max-width: 65%;
              }
            }
          
          &.ai-message {
            justify-content: flex-start;
            
            .message-content {
              background: #f5f5f5;
              color: #333;
              margin-right: 20rpx;
              max-width: 65%;
            }
          }
          
          .message-avatar {
            width: 60rpx;
            height: 60rpx;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32rpx;
            margin: 0 16rpx;
            background: #fff;
            border: 2rpx solid #e0e0e0;
          }
          
          .message-content {
            padding: 24rpx;
            border-radius: 24rpx;
            
            .message-text {
              font-size: 28rpx;
              line-height: 1.4;
              word-break: break-word;
              word-wrap: break-word;
              overflow-wrap: break-word;
            }
            
            .generated-image {
              margin-top: 16rpx;
              
              .ai-image {
                width: 100%;
                height: 400rpx;
                border-radius: 16rpx;
                background: #f0f0f0;
              }
            }
            
            .loading-message {
              display: flex;
              align-items: center;
              gap: 16rpx;
              
              .loading-text {
                font-size: 28rpx;
                color: #666;
              }
              
              .loading-dots {
                display: flex;
                gap: 4rpx;
                
                .dot {
                  animation: loading-dot 1.4s infinite ease-in-out;
                  
                  &:nth-child(1) { animation-delay: -0.32s; }
                  &:nth-child(2) { animation-delay: -0.16s; }
                }
              }
            }
          }
        }
      }
    }
    
    .chat-input-area {
      display: flex;
      align-items: center;
      padding: 24rpx;
      border-top: 1rpx solid #f0f0f0;
      gap: 16rpx;
      
      .chat-input {
        flex: 1;
        padding: 20rpx 24rpx;
        border: 1rpx solid #e0e0e0;
        border-radius: 40rpx;
        font-size: 28rpx;
        background: #fafafa;
      }
      
      .send-btn {
        width: 64rpx;
        height: 64rpx;
        border-radius: 50%;
        background: #34495e;
        color: white;
        border: none;
        font-size: 24rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        
        &:disabled {
          opacity: 0.6;
        }
      }
    }
  }
}

// 相册选择弹窗样式
.album-selector-modal {
  position: fixed; left:0; right:0; top:0; bottom:0;
  z-index: 10001;
  background: rgba(0,0,0,.35);
  transform: translateZ(0);
  backface-visibility: hidden; will-change: transform;
  display: flex; align-items: flex-end;
  
  .selector-content {
    background: white;
    border-top-left-radius: 24rpx; border-top-right-radius: 24rpx;
    width: 100%;
    max-height: 60vh;
    
    .selector-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 40rpx;
      border-bottom: 1rpx solid #f0f0f0;
      
      .selector-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
      }
      
      .close-btn {
        font-size: 48rpx;
        color: #999;
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    
    .album-list {
      max-height: 400rpx;
      
      .album-option {
        display: flex;
        align-items: center;
        padding: 24rpx 40rpx;
        border-bottom: 1rpx solid #f5f5f5;
        
        &:active {
          background: #f8f8f8;
        }
        
        .album-thumb {
          width: 80rpx;
          height: 80rpx;
          border-radius: 12rpx;
          background: #f0f0f0;
          margin-right: 24rpx;
        }
        
        .album-info {
          flex: 1;
          
          .album-name {
            font-size: 32rpx;
            color: #333;
            display: block;
            margin-bottom: 8rpx;
          }
          
          .album-count {
            font-size: 24rpx;
            color: #999;
          }
        }
        
        .select-icon {
          font-size: 32rpx;
          color: #999;
        }
      }
    }
  }
}

// 加载动画
@keyframes loading-dot {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}
</style> 